/* collection:(UseCase)
 * codebase:(Example)
 * toolset:(UserTools)
 * package:hardcoded
 * file:various_facility.groovy
 * 
 * Copyright 2011-2013 Stellabs.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package net.strglr.blu.usertools;

/**
 * Fill a string with the contents of a file, and by default make it a single-line
 */
static def file2Line(String filename, String joiner="", Boolean failonerror=true) {
    def list = []
    def file = new File(filename)
    if (!file.exists() && !failonerror) return "";
    file.eachLine{
        list << it
    };
    return list.join(joiner);
}


/**
 * Create a deep map from a property shallow map
 */
static def prop2map(Map prop) {
    def es = prop.entrySet();
    if (es.isEmpty()) return null;
    Map mapmap = new HashMap();
    es.each{
        putMapKeylist(mapmap, it.key.split("\\.").toList(), it.value);
    }
    return mapmap;
}

static Map putMapKeylist(Map mapmap, List list, Object value) {
    Object head = list.remove(0);
    Object v = mapmap.get(head);
    if (v != null) {
        if (list.isEmpty()) {
            assert v instanceof Map;
            ((Map)v).put("",value);
        } else {
            Map m;
            if (v instanceof Map) m = (Map)v;
            else {
                m = new HashMap();
                m.put("",v);
            }
            v = putMapKeylist(m, list, value);
        }
    }
    else if (list.isEmpty()) v = value;
    else v = putMapKeylist(new HashMap(), list, value);

    mapmap.put(head, v);
    return mapmap;
}


/**
 * Replace the ${keys} of a template String with the applicable values found in a deep map
 */
static def applyTemplate(tmpl, deepMap) {
    return new groovy.text.SimpleTemplateEngine().createTemplate(tmpl).make(deepMap).toString();
}

